using System;
using System.Text.RegularExpressions;
using System.Configuration;
using System.Collections.Generic;

namespace IfSoft.IfNuke.Web.UrlRewriter
{
    /// <summary>
    /// Provides a rewriting HttpModule.
    /// </summary>
    public class ModuleRewriter : BaseModuleRewriter
    {
        /// <summary>
        /// This method is called during the module's BeginRequest event.
        /// </summary>
        /// <param name="requestedRawUrl">The RawUrl being requested (includes path and querystring).</param>
        /// <param name="app">The HttpApplication instance.</param>
        protected override void Rewrite(System.Web.HttpApplication app)
        {
            // log information to the Trace object.
            app.Context.Trace.Write("ModuleRewriter", "Entering ModuleRewriter");

            string originalUrl = app.Request.Url.ToString().ToLower();
            string requestedPath = app.Request.Path;
            string sendToUrl = string.Empty;
            RewriterRuleCollection rules = RewriterConfiguration.GetConfig().Rules;

            for (int i = 0; i < rules.Count; i++)
            {
                // get the pattern to look for, and Resolve the Url (convert ~ into the appropriate directory)
                string lookFor = "^" + RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, rules[i].LookFor) + "$";
                Regex re = new Regex(lookFor, RegexOptions.IgnoreCase);
                string url = string.Empty;
                if (originalUrl.IndexOf("www.") >= 0)
                    url = originalUrl;
                else
                    url = requestedPath;

                if (re.IsMatch(url))
                {
                    sendToUrl = RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, re.Replace(url, rules[i].SendTo));
                    // log rewriting information to the Trace object
                    app.Context.Trace.Write("ModuleRewriter", "Rewriting URL to " + sendToUrl);
                    // Rewrite the URL
                    RewriterUtils.RewriteUrl(app.Context, sendToUrl);
                    break;
                }
            }

            // Log information to the Trace object
            app.Context.Trace.Write("ModuleRewriter", "Exiting ModuleRewriter");
        }
       
    }
}
